package com.junzhiit.nengji.shop.service.impl;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.junzhiit.nengji.bo.GoodsBO;
import com.junzhiit.nengji.bo.GoodsSkuItemsBO;
import com.junzhiit.nengji.bo.LabelBO;
import com.junzhiit.nengji.dao.GoodsDAO;
import com.junzhiit.nengji.dao.GoodsSkuItemsDAO;
import com.junzhiit.nengji.dao.LabelDAO;
import com.junzhiit.nengji.dao.SkuContentDAO;
import com.junzhiit.nengji.dao.TagDAO;
import com.junzhiit.nengji.model.Goods;
import com.junzhiit.nengji.model.SkuContent;
import com.junzhiit.nengji.model.Tag;
import com.junzhiit.nengji.model.enums.GoodsHistoryType;
import com.junzhiit.nengji.model.enums.GoodsImagesType;
import com.junzhiit.nengji.model.enums.Is;
import com.junzhiit.nengji.shop.service.GoodsHistoryService;
import com.junzhiit.nengji.shop.service.GoodsService;
import com.junzhiit.nengji.shop.web.exception.GoodsNotFoundException;
import com.junzhiit.nengji.shop.web.exception.SkuContentNotFoundException;
import com.junzhiit.nengji.shop.web.vo.GoodsHistoryAEVO;
import com.junzhiit.nengji.shop.web.vo.GoodsInfoVO;
import com.junzhiit.nengji.shop.web.vo.GoodsVO;
import com.junzhiit.nengji.shop.web.vo.ListVO;
import com.junzhiit.nengji.shop.web.vo.ResultVO;
import com.junzhiit.nengji.shop.web.vo.SkuContentVO;
import com.junzhiit.nengji.shop.web.vo.SkuItemsVO;
import com.junzhiit.nengji.shop.web.vo.SkuVO;
import com.junzhiit.nengji.shop.web.vo.TagVO;

@Service
public class GoodsServiceImpl extends BaseServiceImpl implements GoodsService {

	@Autowired
	private GoodsDAO goodsDAO;

	@Autowired
	private GoodsSkuItemsDAO goodsSkuItemsDAO;

	@Autowired
	private SkuContentDAO skuContentDAO;

	@Autowired
	private GoodsHistoryService goodsHistoryService;
	
	@Autowired
	private LabelDAO labelDAO;
	
	@Autowired
	private TagDAO tagDAO;


	@Override
	public ResultVO findGoods(String goodsName, String typeId, String userId, String shopId, Integer status) {
		ResultVO result = new ResultVO();
		List<GoodsBO> list = goodsDAO.findGoods(goodsName, typeId, shopId, status);
		List<GoodsVO> goodsVOList = new ArrayList<GoodsVO>();
		List<GoodsHistoryAEVO> goodsHistoryAEVOList = new ArrayList<GoodsHistoryAEVO>();
		for (GoodsBO goodsBO : list) {
			GoodsVO goodsVO = new GoodsVO();
			BeanUtils.copyProperties(goodsBO, goodsVO);
			goodsVOList.add(goodsVO);

			GoodsHistoryAEVO goodsHistoryAEVO = new GoodsHistoryAEVO();
			goodsHistoryAEVO.setKey(userId + "-" + goodsBO.getId() + "-" + GoodsHistoryType.EXPOSURE.toIntValue());
			goodsHistoryAEVO.setGoodsId(goodsBO.getId());
			goodsHistoryAEVO.setShopId(goodsBO.getShopId());
			goodsHistoryAEVO.setUserId(userId);
			goodsHistoryAEVO.setNumber(1);
			goodsHistoryAEVO.setCreatedTime(new Date());
			goodsHistoryAEVO.setType(GoodsHistoryType.EXPOSURE.toIntValue());
			goodsHistoryAEVOList.add(goodsHistoryAEVO);
		}

		if (StringUtils.isNotBlank(userId)) {
			goodsHistoryService.add(goodsHistoryAEVOList);
		}

		result.setData(goodsVOList);
		return result;
	}

	@Override
	@Transactional
	public ListVO findAll(String userId, String shopId, Integer status, Integer goodsSearchType,
			Integer pageNumber, Integer maxPageRow) {

		List<GoodsBO> list = goodsDAO.findAll(shopId, status, goodsSearchType, pageNumber, maxPageRow);
		List<GoodsVO> goodsVOList = new ArrayList<GoodsVO>();
		List<GoodsHistoryAEVO> goodsHistoryAEVOList = new ArrayList<GoodsHistoryAEVO>();
		for (GoodsBO goodsBO : list) {
			GoodsVO goodsVO = new GoodsVO();
			BeanUtils.copyProperties(goodsBO, goodsVO);
			goodsVOList.add(goodsVO);

			GoodsHistoryAEVO goodsHistoryAEVO = new GoodsHistoryAEVO();
			goodsHistoryAEVO.setKey(userId + "-" + goodsBO.getId() + "-" + GoodsHistoryType.EXPOSURE.toIntValue());
			goodsHistoryAEVO.setGoodsId(goodsBO.getId());
			goodsHistoryAEVO.setShopId(shopId);
			goodsHistoryAEVO.setUserId(userId);
			goodsHistoryAEVO.setNumber(1);
			goodsHistoryAEVO.setCreatedTime(new Date());
			goodsHistoryAEVO.setType(GoodsHistoryType.EXPOSURE.toIntValue());
			goodsHistoryAEVOList.add(goodsHistoryAEVO);
		}

		if (StringUtils.isNotBlank(userId)) {
			goodsHistoryService.add(goodsHistoryAEVOList);
		}

		Goods goods = new Goods();
		goods.setShopId(shopId);
		int totalCount = goodsDAO.findAllByPageTotalCount(shopId, status, goodsSearchType);

		ListVO listVO = new ListVO();
		listVO.setIndex(pageNumber);
		listVO.setCount(totalCount);
		listVO.setList(goodsVOList);

		return listVO;
	}


	@Override
	public ResultVO checkStock(String goodsInfo) {
		ResultVO result = new ResultVO();
		String[] goodsArray = goodsInfo.split(";");

		List<String> list = new ArrayList<>();
		for (int i = 0; i < goodsArray.length; i++) {
			String[] goodsObj = goodsArray[i].split("_");

			// number_price_goodsId_skuContentId
			Integer number = Integer.valueOf(goodsObj[0]);
			String goodsId = goodsObj[1];
			String skuContentId = "";
			if (goodsObj.length == 4) {
				skuContentId = goodsObj[3];
			}

			Integer stock = 0;
			Goods goods = goodsDAO.query(goodsId);
			if (goods == null) {
				throw new GoodsNotFoundException("商品没找到");
			}

			if (StringUtils.isNotBlank(skuContentId)) {
				SkuContent skuContent = skuContentDAO.query(skuContentId);
				if (skuContent == null) {
					throw new SkuContentNotFoundException("sku规格组合没找到");
				}
				stock = skuContent.getStock();
			} else {
				stock = goods.getStock();
			}

			if (number > stock) {
				list.add(goods.getName());
			}
		}
		result.setData(list);
		return result;
	}

	@Override
	public ResultVO findGoodsInfoNew(String code, String userId) {
		ResultVO result = new ResultVO();

		GoodsBO goodsBO = goodsDAO.getGoodsByCode(code);
		if (goodsBO == null) {
			throw new GoodsNotFoundException("商品不存在");
		}

		GoodsInfoVO goodsInfoVO = new GoodsInfoVO();
		BeanUtils.copyProperties(goodsBO, goodsInfoVO);
		goodsInfoVO.setPriceRange(goodsInfoVO.getPrice().toString());

		/*if (goodsBO.getPostageType() == PostageType.TEMPLATE.toIntValue()
				&& StringUtils.isNoneBlank(goodsBO.getPostageTemplateId())) {
			double basicPostage = postageConditionDAO.getMinPostageCondition(goodsBO.getPostageTemplateId());
			goodsInfoVO.setPostagePrice(Format.decimal(basicPostage));
		}*/

		// 查询商品轮播图
		List<String> cardImgList = goodsDAO.getFileNameByCode(code, GoodsImagesType.CARD);
		goodsInfoVO.setCardImgList(cardImgList);
		// 查询商品详情图
		List<String> detailImgList = goodsDAO.getFileNameByCode(code, GoodsImagesType.DETAIL);
		goodsInfoVO.setDetailImgList(detailImgList);
		// 统计商品的评价
//		UserEvaluateCountBO evaluateCount = userEvaluateDAO.findEvaluateCount(goodsInfoVO.getId());
//		goodsInfoVO.setEvaluateCount(evaluateCount);

		// 最多最新2条5星不带图片的好评
//		List<UserEvaluateBO> evaluateList = userEvaluateDAO.findWithinRangeUserEvaluate(goodsInfoVO.getId());
//		List<UserEvaluateVO> evaluateListVO = new ArrayList<UserEvaluateVO>();
//		if (evaluateList != null) {
//			for (int i = 0; i < evaluateList.size(); i++) {
//				UserEvaluateBO userEvaluateVO = evaluateList.get(i);
//				if (userEvaluateVO.getIsAnonymity() == Is.YES.toIntValue()) {
//					userEvaluateVO.setNickName("匿名用户");
//					userEvaluateVO.setHeadImgUrl("https://file.legeclub.com/evaluate/anonymous_head.png");
//				}
//				UserEvaluateVO vo = new UserEvaluateVO();
//				BeanUtils.copyProperties(userEvaluateVO, vo);
//				evaluateListVO.add(vo);
//			}
//		}
//
//		goodsInfoVO.setEvaluateList(evaluateListVO);

		// 判断是否开启sku
		if (goodsInfoVO.getIsOpenSku() == Is.YES.toIntValue()) {

			List<GoodsSkuItemsBO> goodsSkuItemsBOs = goodsSkuItemsDAO.queryGoodsSkuItemsBO(goodsBO.getId());

			Map<String, SkuVO> map = new LinkedHashMap<String, SkuVO>();

			for (GoodsSkuItemsBO bo : goodsSkuItemsBOs) {
				SkuVO skuVO = map.get(bo.getSkuId());
				if (skuVO == null) {
					skuVO = new SkuVO();
					skuVO.setId(bo.getSkuId());
					skuVO.setName(bo.getName());
					skuVO.setIsOpenImage(bo.getIsOpenImage());
					List<SkuItemsVO> skuItemsList = new ArrayList<SkuItemsVO>();
					skuVO.setSkuItemsList(skuItemsList);
					map.put(skuVO.getId(), skuVO);
				}

				SkuItemsVO skuItemsVO = new SkuItemsVO();
				skuItemsVO.setId(bo.getSkuItemsId());
				skuItemsVO.setSkuId(bo.getSkuId());
				skuItemsVO.setStandard(bo.getStandard());
				skuItemsVO.setImage(bo.getImage());
	            skuItemsVO.setIsOpenImage(bo.getIsOpenImage());
				skuVO.getSkuItemsList().add(skuItemsVO);
			}
			Collection<SkuVO> data = map.values();
			goodsInfoVO.setSkuList(data);

			// 查询skuContent
			List<SkuContent> SkuContentList = skuContentDAO.findSkuContentByGoodsId(goodsBO.getId());
			List<SkuContentVO> skuContentVOList = new ArrayList<SkuContentVO>();
			int stock = 0;
			List<Double> priceList = new ArrayList<Double>();
			for (SkuContent skuContent : SkuContentList) {
				SkuContentVO skuContentVO = new SkuContentVO();
				skuContent.setStandards(skuContent.getStandards().replace("+", ";"));
				BeanUtils.copyProperties(skuContent, skuContentVO);
				stock += (skuContent.getStock() == null) ? 0 : skuContent.getStock();
				priceList.add(skuContent.getPrice());
				skuContentVOList.add(skuContentVO);
			}
			goodsInfoVO.setStock(stock);
			if (priceList.size() > 0) {
				Double maxPrice = Collections.max(priceList);
				Double minPrice = Collections.min(priceList);
				if (maxPrice != minPrice) {
					goodsInfoVO.setPriceRange((minPrice + "-" + maxPrice));
				} else {
					goodsInfoVO.setPriceRange(minPrice.toString());
				}
			}
			goodsInfoVO.setSkuContentList(skuContentVOList);
		}
		
		//取得商品的参数详情
	    List<LabelBO> labelList = labelDAO.getGoodsAll(goodsBO.getId());
	    goodsInfoVO.setLabelList(labelList);
	    
	    //取得标签属性(服务承诺等)
	    List<TagVO> tagVOList = new ArrayList<TagVO>();
	    List<Tag> tagList = tagDAO.getAllByGoodsId(goodsBO.getId());
	    for(int i=0,t=tagList.size();i<t;i++){
	    	Tag tag = tagList.get(i);
	    	TagVO tagVO = new TagVO();
	    	BeanUtils.copyProperties(tag, tagVO);
	    	tagVOList.add(tagVO);
	    }
	    goodsInfoVO.setTagVOList(tagVOList);
		
		//当用户ID存在
		if (StringUtils.isNotBlank(userId)) {

			// 查询当前购物车商品数
//			Integer count = cartDAO.sumGoodsNumber(userId);
//			goodsInfoVO.setCount(count);

			// 查询商品是否被用户收藏
//			Favorite favorite = favoriteDAO.getFavorite(userId, goodsBO.getId());
//			if (favorite != null) {
//				goodsInfoVO.setFavorite(true);
//				goodsInfoVO.setFavoriteId(favorite.getId());
//			} else {
//				goodsInfoVO.setFavorite(false);
//			}
//			// 商家优惠卷
//			List<CouponsDetailsVO> voList = new ArrayList<CouponsDetailsVO>();
//			List<CouponsDetailsBO> couponsList = couponsDAO.getUserIdReceiveCouponsByshopId(userId,
//					goodsBO.getShopId());
//			for (int i = 0; i < couponsList.size(); i++) {
//				CouponsDetailsBO cdBo = couponsList.get(i);
//				CouponsDetailsVO cdVo = new CouponsDetailsVO();
//				cdVo.setCouponsType(cdBo.getType());
//				cdVo.setIsOpenRandom(cdBo.getIsOpenRandom());
//				cdVo.setPlatform(cdBo.getPlatform());
//				if (cdBo.getPlatform() != null) {
//					if (cdBo.getPlatform() == 0) {
//						cdVo.setOwnName(cdBo.getShopName());
//					} else if (cdBo.getPlatform() == 2) {
//						cdVo.setOwnName("平台劵");
//					}
//				}
//				// 等于0为指定金额
//				if (cdBo.getType() == 0) {
//					// 是否为随机劵为1则是随机劵
//					cdVo.setCouponsName("现金劵");
//					if (cdBo.getIsOpenRandom() == 1) {
//						cdVo.setFaceValue(
//								this.formatDouble(cdBo.getStartPrice()) + "~" + this.formatDouble(cdBo.getEndPrice()));
//					} else {
//						cdVo.setFaceValue(this.formatDouble(cdBo.getPrice()));
//					}
//				} else {
//					// 等于1为折扣
//					cdVo.setCouponsName("折扣劵");
//					cdVo.setFaceValue(this.formatDouble(cdBo.getDiscount()));
//				}
//				// 等于0为无门槛
//				if (cdBo.getThreshold() == 0) {
//					cdVo.setRemarks("无门槛");
//				} else {
//					// 等于1为有门槛
//					cdVo.setRemarks("满" + this.formatDouble(cdBo.getFullPriceReduction()) + "元可用");
//				}
//				cdVo.setId(cdBo.getId());
//				cdVo.setValidEndTime(cdBo.getValidEndTime());
//				voList.add(cdVo);
//			}
//			goodsInfoVO.setCouponsList(voList);

			GoodsHistoryAEVO goodsHistoryAEVO = new GoodsHistoryAEVO();
			goodsHistoryAEVO.setKey(userId + "-" + goodsInfoVO.getId() + "-" + GoodsHistoryType.VIEW.toIntValue());
			goodsHistoryAEVO.setGoodsId(goodsInfoVO.getId());
			goodsHistoryAEVO.setShopId(goodsInfoVO.getShopId());
			goodsHistoryAEVO.setUserId(userId);
			goodsHistoryAEVO.setNumber(1);
			goodsHistoryAEVO.setCreatedTime(new Date());
			goodsHistoryAEVO.setType(GoodsHistoryType.VIEW.toIntValue());
			goodsHistoryService.add(goodsHistoryAEVO);
		}

		result.setData(goodsInfoVO);
		return result;
	}

	public String formatDouble(double number) {
		String moneyStr = String.valueOf(number);
		String[] num = moneyStr.split("\\.");
		if (num.length == 2) {
			if (Integer.parseInt(num[1]) > 0) {
				return new DecimalFormat("#.#").format(number);
			} else {
				return num[0];
			}
		} else {
			return num[0];
		}
	}

}
